#include "PerlinNoise.h"

static int permutation[PERMUTATION_SIZE * 2];

void initPermutation()
{
	for (int i = 0; i < PERMUTATION_SIZE; i++)
		permutation[i] = i;

	for (int i = PERMUTATION_SIZE - 1; i > 0; i--) {
		int j = rand() % (i + 1);
		int temp = permutation[i];
		permutation[i] = permutation[j];
		permutation[j] = temp;
	}

	for (int i = 0; i < PERMUTATION_SIZE; i++)
		permutation[PERMUTATION_SIZE + i] = permutation[i];
}

int grad(int hash, double x)
{
	int h = hash & 15;
	return (h < 8 ? x : -x);
}

double fade(double t)
{
	return t * t * t * (t * (t * 6 - 15) + 10);
}

double lerp(double a, double b, double t)
{
	return a + t * (b - a);
}

double perlinNoise1d(double x)
{
	int X = (int) floor(x) & (PERMUTATION_SIZE - 1);

	double x_off = x - floor(x);

	double u = fade(x_off);

	int aa = permutation[permutation[X]];
	int ab = permutation[permutation[X + 1]];

	double gradAA = grad(aa, x_off);
	double gradAB = grad(ab, x_off - 1);

	return lerp(gradAA, gradAB, u);
}

double perlinNoise2d(double x, double y)
{
	return 0;
}

double perlinNoise3d(double x, double y, double z)
{
	return 0;
}

